package com.example.Controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Service.impl.UserServiceImpl;
import com.example.dao.DepartmentMapper;
import com.example.dao.LeaveemployeeMapper;
import com.example.dao.UserMapper;
import com.example.exception.MyException;
import com.example.pojo.Department;
import com.example.pojo.Leaveemployee;
import com.example.pojo.User;
import com.example.util.MD5;
import com.example.util.PasswordUtils;
import com.example.util.Result;
import com.example.util.ThreadLocalUtil;
import com.example.util.sms.SmsUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户管理")
@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LeaveemployeeMapper leaveemployeeMapper;

    @Autowired
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private DepartmentMapper departmentMapper;

    @RequestMapping("/selectAllByDepartment")
    public Result selectAllByDepartment() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("department_id", "COUNT(*) as count");
        queryWrapper.groupBy("department_id");
        List<User> list = userMapper.selectList(queryWrapper);
        for (User user : list) {
            if (user.getDepartmentId() != null) {
                QueryWrapper<Department> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("department_id", user.getDepartmentId());
                Department department=departmentMapper.selectOne(queryWrapper1);
                user.setDepartmentName(department.getDepartmentName());
            }else {
                user.setDepartmentName("无部门");
            }
        }
        return new Result("200","获取部门数据",list);
    }
    @RequestMapping("/login")
    public Result login(@RequestBody User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());
        User user1 = userMapper.selectOne(queryWrapper);
        String token = "";
        if (user1==null){
            throw new MyException("101","用户不存在");
        }
        //加盐
        String slat = user1.getPassword().split("\\$")[0];
        String encrypt = PasswordUtils.encrypt(MD5.encrypt(user.getPassword()),slat);

        if (!user1.getPassword().equals(encrypt)){
            throw new MyException("102","密码不正确");
        }

        token = UUID.randomUUID().toString();
        String json = JSONObject.toJSONString(user1);
        stringRedisTemplate.opsForValue().set(token,json,1, TimeUnit.HOURS);
        Long id = Long.valueOf(user1.getId());
        ThreadLocalUtil.setCurrentId(id);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user1);
        return new Result("200","登陆成功",map);
    }




    /**
     * 生产部门  ---> 生产人员
     */
    @GetMapping("/selectAllPage")
    public Result selectAllProduct(User user, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "8") Integer pageSize){
        PageInfo<User> pageInfo = userService.selecAllProduct(user,pageNum,pageSize);
        return new Result("200","查询成功",pageInfo);
    }

    //添加生产部门信息
    @PostMapping("/addProduct")
    public Result addProduct(@RequestBody User user) {
        userService.addProduct(user);
        return new Result("200","添加成功");
    }

    //修改用户信息
    @PutMapping("/updateProduct")
    public Result updateProduct(@RequestBody User user){
        userService.updateProduct(user);
        return new Result("200","修改成功");
    }

    /**
     * it部门 ---> 全部it部门人员
     */
    @GetMapping("/selectAllItPage")
    public Result selectAllItPage(User user,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<User> pageInfo = userService.selectAllItPage(user,pageNum,pageSize);
        return new Result("200","查询成功",pageInfo);
    }




//    @GetMapping("sendCode")
//    public Result sendCode(String phone){
//        String code = MathUtils.random(); //生成验证码
//        System.out.println(code);
//        boolean bo = false;
//        try {
//            stringRedisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
//            bo = smsUtils.sendMessage(phone,code); // 发送验证码
//        }catch (Exception e){
//            bo = false;
//            throw new RuntimeException(e);
//        }
//        if (!bo){
//            return new Result("300","短信发送失败");
//        }
//        return new Result("200","短信发送成功");
//    }
//


     @GetMapping("/selectAll") //员工的信息查询
     public Result getUsers(@RequestParam(value = "name",defaultValue ="")String name,
                            @RequestParam(value = "id",defaultValue ="")Integer id,
                            @RequestParam(value = "departmentId",defaultValue ="")Integer departmentId,
                            @RequestParam(value = "positionId",defaultValue ="")Integer positionId,
                            @RequestParam(value = "PageNum",defaultValue ="1")Integer PageNum,
                            @RequestParam(value = "PageSize",defaultValue ="14")Integer PageSize){
         PageInfo<User> users = userService.selectAll(name, id, departmentId, positionId, PageNum, PageSize);

         return new Result("200", "查询成功",users);
    }

    @PostMapping("/registerAccount") //人事添加  //注册
    public Result resgist(@RequestBody User user){
        //MD5加密
        LocalDateTime dateTime = LocalDateTime.now();  //当天时间


        if (user!=null){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("name",user.getName());
            User user1 = userMapper.selectOne(userQueryWrapper); //查询用户
            if (user1!=null){
                return  new Result("200","查询成功");
            }

            user.setCreateDate(dateTime);
            user.setPassword(PasswordUtils.encrypt(MD5.encrypt(user.getPassword())));
            int rows = userMapper.insert(user);
            if (rows>0){
                return new Result("200","注册成功");
            }
            return new Result("202","注册失败");
        }
        return new Result("203","注册失败");
    }

    @RequestMapping("/selectOne") //通过id查询用户信息
    public  Result selectOne(Integer id){
        User user = userService.selectOne(id);
        return new Result("200","查询成功",user);
    }


    @RequestMapping("/updateUserInfo") //修改用户信息
    public  Result updateUserInfo(@RequestBody User user){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",user.getId());
        int update = userMapper.update(user, wrapper);
        return new Result("200","修改成功",update);
    }

    @RequestMapping("/deleteUser") //删除用户信息  //辞退
    public  Result deleteUser(Integer id){
        LocalDateTime localDateTime = LocalDateTime.now();


        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);

        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id",id);



        User user = userMapper.selectOne(id);

        System.out.println(user);
        int delete = userMapper.delete(wrapper);
        Leaveemployee leaveemployee = new Leaveemployee();

        leaveemployee.setName(user.getName());
        leaveemployee.setDepartmentId(user.getDepartmentId());
        leaveemployee.setPositionId(user.getPositionId());
        leaveemployee.setSex(Integer.valueOf(user.getSex()));
        leaveemployee.setStatus(1);
        leaveemployee.setLeaveDate(localDateTime);

        if (delete>0){
             int insert = leaveemployeeMapper.insert(leaveemployee);
            if(insert>0){
                return new Result("200","添加成功",insert);
            }
            return new Result("200","删除成功",delete);
        }
        return new Result("406","删除失败",delete);
    }


    @RequestMapping("/JumpInfo")  //查询名字
    public  Result  JumpInfo(@RequestParam(value = "name",defaultValue = "") String name){
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("name",name);
        User user1 = userMapper.selectOne(wrapper);
        if (user1.getPositionId()<3){
            return  new Result("200","查询成功","权限不足");
        }
        User user = userService.selectJump(name);
        return  new Result("200","查询成功",user);
    }


    @RequestMapping("updateUserDepart")  //修改用户部门   //bug
    public  Result updateUserDepart(@RequestBody User user){
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(user);
        User user1 = new User();
        user1.setCreateDate(dateTime);
        user1.setDepartmentId(user.getDepartmentId());
        user1.setPositionId(user.getPositionId());
        System.out.println(user.getCreateDate());
        user1.setCreateDate(user.getCreateDate());
        user1.setCreateBy(user.getCreateBy());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName());
        int update = userMapper.update(user1,wrapper);
        return new Result("200","修改成功",update);
    }



}
